package com.platform.controller;

import com.platform.entity.GoodsEntity;
import com.platform.entity.SysDeptEntity;
import com.platform.service.GoodsService;
import com.platform.entity.GoodsCategoryEntity;
import com.platform.service.GoodsCategoryService;
import com.platform.service.CategoryService;

import com.platform.entity.AgentEntity;
import com.platform.service.AgentService;
import com.platform.service.SysDeptService;
import com.platform.utils.PageUtils;
import com.platform.utils.Query;
import com.platform.utils.R;
import com.qiniu.util.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-21 21:19:49
 */
@RestController
@RequestMapping("goods")
public class GoodsController extends AbstractController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("goods:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        query.put("isDelete", 0);

        //中大团队扩展，只可获取商家自己的商品，rootDeptId为1为超级管理员，可获取所有商品
        if (!isSuperAdmin()) {
            query.put("rootDeptId", getRootDept().getDeptId());
        }

        List<GoodsEntity> goodsList = goodsService.queryList(query);

        //这段代码有bug，先注释掉
        if(goodsList != null && goodsList.size() > 0) {
            for (int i = 0; i < goodsList.size(); i++) {
                GoodsEntity goodsEntity = goodsList.get(i);
                List<Integer> categoryIds = goodsCategoryService.queryObject(goodsEntity.getId());
                List<String> categoryNames = categoryService.queryNamesByIds(categoryIds);
                if(categoryNames != null && categoryNames.size() > 0) {
                    goodsEntity.setCategoryName(StringUtils.join(categoryNames, ","));
                }
            }
        }

        int total = goodsService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 中大团队扩展
     * 只列出
     * @param params
     * @return
     */
    @RequestMapping("/agentList")
    public R agentList(@RequestParam Map<String, Object> params) {
        Query query = new Query(params);

        //代理商代理等級，不同的代理等级显示不同的商品
        Long agent_id = getRootDept().getDeptId();
        Long vendor_id = Long.valueOf(String.valueOf(params.get("rootDeptId")));
        List<AgentEntity> agent = agentService.queryExistAgentApply(vendor_id,agent_id);
        int cert_level = 1;
        for (AgentEntity a : agent) {
            cert_level = a.getCertLevel();
        }
        query.put("cert_level", cert_level);


        //查询商品列表数据
        query.put("isDelete", 0);
        query.put("name", params.get("key"));
        query.put("rootDeptId", params.get("rootDeptId"));  //供货商商家ID

        List<GoodsEntity> goodsList = goodsService.queryAgentList(query);



        //这段代码有bug，先注释掉
        /*if(goodsList != null && goodsList.size() > 0) {
            for (int i = 0; i < goodsList.size(); i++) {
                GoodsEntity goodsEntity = goodsList.get(i);
                List<Integer> categoryIds = goodsCategoryService.queryObject(goodsEntity.getId());
                List<String> categoryNames = categoryService.queryNamesByIds(categoryIds);
                if(categoryNames != null && categoryNames.size() > 0) {
                    goodsEntity.setCategoryName(StringUtils.join(categoryNames, ","));
                }
            }
        }*/


        int total = goodsService.queryAgentTotal(query);

        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 新建信息
     */
    @RequestMapping("/newGoods")
    public R newGoods() {
        R r = new R();

        GoodsEntity goodsEntity = new GoodsEntity();
        goodsEntity.setSaleType("x");
        goodsEntity.setAccessUserGrade(Integer.valueOf(1));
        goodsEntity.setPrimaryPicUrl("");
        goodsEntity.setListPicUrl("");
        goodsEntity.setIsOnSale(Integer.valueOf(1));
        goodsEntity.setIsNew(Integer.valueOf(1));
        goodsEntity.setIsAllowAgent(Integer.valueOf(1));
        goodsEntity.setIsHot(Integer.valueOf(0));
        goodsEntity.setSortOrder(Integer.valueOf(1));

        //设定当前商品访问对象
        SysDeptEntity dept = sysDeptService.queryObject(getRootDept().getDeptId());
        if(dept.getRootType().intValue() == 0 || dept.getRootType().intValue() == 1){
            goodsEntity.setPriceType(Integer.valueOf(0)); //旗舰店或批发店，默认是三级阶梯价格
        }
        else{
            goodsEntity.setPriceType(Integer.valueOf(1)); //零售店，默认是三级阶梯价格
        }

        r.put("currShop", dept);
        r.put("goods", goodsEntity);

        return r;
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("goods:info")
    public R info(@PathVariable("id") Integer id) {
        R r = new R();

        GoodsEntity goodsEntity = goodsService.queryObject(id);

        List<Integer> categoryIds = goodsCategoryService.queryObject(goodsEntity.getId());

        SysDeptEntity dept = sysDeptService.queryObject(getRootDept().getDeptId());
        r.put("currShop", dept);

        r.put("goods", goodsEntity);
        r.put("categoryIds", categoryIds); //中大团队扩展，用于支持商品类型多选下拉的值回显

        return r;
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("goods:save")
    public R save(@RequestBody GoodsEntity goods) {
        //中大团队扩展，保存所属商家ID
        goods.setRootDeptId(getRootDept().getDeptId());

        //保存商品详细信息
        goodsService.save(goods);

        //先保存商品，然后重新建立商品和分类关联关系
        if(goods.getCategoryIds() != null && goods.getCategoryIds().trim().length() > 0) {
            String[] categoryIdArray = goods.getCategoryIds().split("#");
            for (int i = 0; i < categoryIdArray.length; i++) {
                GoodsCategoryEntity goodsCategoryEntity = new GoodsCategoryEntity();
                goodsCategoryEntity.setCategoryId(Integer.parseInt(categoryIdArray[i]));
                goodsCategoryEntity.setGoodId(goods.getId());
                goodsCategoryService.save(goodsCategoryEntity);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("goodsId", goods.getId());
        return R.ok(map);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("goods:update")
    public R update(@RequestBody GoodsEntity goods) {
        //中大团队扩展，保存所属商家ID
        goods.setRootDeptId(getRootDept().getDeptId());

        //重新建立商品和分类关联关系
        if(goods.getCategoryIds() != null && goods.getCategoryIds().trim().length() > 0) {
            String[] categoryIdArray = goods.getCategoryIds().split("#");

            goodsCategoryService.deleteByGoodsId(goods.getId());
            for (int i = 0; i < categoryIdArray.length; i++) {
                GoodsCategoryEntity goodsCategoryEntity = new GoodsCategoryEntity();
                goodsCategoryEntity.setCategoryId(Integer.parseInt(categoryIdArray[i]));
                goodsCategoryEntity.setGoodId(goods.getId());
                goodsCategoryService.save(goodsCategoryEntity);
            }
        }

        //更新商品详细信息
        goodsService.update(goods);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("goods:delete")
    public R delete(@RequestBody Integer[] ids) {
        goodsService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        params.put("isDelete", 0);
        //中大团队扩展，只可获取商家自己的商品
        params.put("rootDeptId", getRootDept().getDeptId());
        List<GoodsEntity> list = goodsService.queryList(params);

        return R.ok().put("list", list);
    }


    /**
     * 商品回收站
     *
     * @param params
     * @return
     */
    @RequestMapping("/historyList")
    public R historyList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        query.put("isDelete", 1);
        //中大团队扩展，只可获取商家自己的商品
        query.put("rootDeptId", getRootDept().getDeptId());
        List<GoodsEntity> goodsList = goodsService.queryList(query);
        int total = goodsService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(goodsList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 商品从回收站恢复
     */
    @RequestMapping("/back")
    @RequiresPermissions("goods:back")
    public R back(@RequestBody Integer[] ids) {
        goodsService.back(ids);

        return R.ok();
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {

        params.put("isDelete", 0);
        //中大团队扩展，只可获取商家自己的商品
        params.put("rootDeptId", getRootDept().getDeptId());
        int sum = goodsService.queryTotal(params);
        return R.ok().put("goodsSum", sum);
    }

    /**
     * 上架
     */
    @RequestMapping("/enSale")
    public R enSale(@RequestBody Integer id) {
        goodsService.enSale(id);

        return R.ok();
    }

    /**
     * 下架
     */
    @RequestMapping("/unSale")
    public R unSale(@RequestBody Integer id) {
        goodsService.unSale(id);

        return R.ok();
    }
}
